1

Create a matrix with 8 rows and 8 columns filled with random numbers in a range between 1 and 1000.
You can use the sample() function to create the numbers.
library(dplyr)

fancy_matrix <-
  sample(1:1000, 8*8, replace = TRUE) %>% 
  matrix(nrow = 8, ncol = 8)

fancy_matrix
##      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
## [1,]  152  100  554  351  306  504  822  804
## [2,]  323  760   96  701  693   86  699  268
## [3,]   90  977  205  726  674   35  565  731
## [4,]  972  658  952  170  117  367  739  571
## [5,]  417  268  638  896  883  813  476  864
## [6,]   52  926  725  461  734  999  209  436
## [7,]  894  406  942  342    3  152  929  208
## [8,]  499  834  200  656  737  849   25  527

2

Now use this matrix to create a raster layer and plot it.
The terra::rast() function can be fed with matrices to create a raster layer.
library(terra)

fancy_raster_layer <-
  terra::rast(fancy_matrix)

terra::plot(fancy_raster_layer)

The terra::rast() function can not only be used to create raster data on the fly, which is also not very interesting. Instead, we can use it to import already prepared data.

3

Import one of the raster .tiff files in the ./data folder of the workshop directory.
Make sure your file paths are set correctly. You can check them with getwd(). Setting is done with setwd().
immigrants_cologne <-
  terra::rast("./data/immigrants_cologne.tif")

4

Import the data on Immigrants, Germans, and Inhabitants. Add up the Immigrants and Germans to a new layer. Then subtract this new layer from the Inhabitants layer to check whether the inhabitant layer is the same as the sum of immigrants and Germans. Is it?
You can handle raster layers as any simple data table using + and - operators.
# load all layers
immigrants_cologne <-
  terra::rast("./data/immigrants_cologne.tif")

germans_cologne <-
  terra::rast("./data/germans_cologne.tif")

inhabitants_cologne <-
  terra::rast("./data/inhabitants_cologne.tif")

# create sum layer
immigrants_germans_sum <-
  immigrants_cologne + germans_cologne

# create difference layer
difference_layer <-
  inhabitants_cologne - immigrants_germans_sum

difference_layer
## class       : SpatRaster 
## dimensions  : 289, 264, 1  (nrow, ncol, nlyr)
## resolution  : 100, 100  (x, y)
## extent      : 4094850, 4121250, 3084050, 3112950  (xmin, xmax, ymin, ymax)
## coord. ref. : ETRS89-extended / LAEA Europe (with axis order normalized for visualization) 
## source      : memory 
## name        : inhabitants_cologne 
## min value   :                  -2 
## max value   :                   0
# get a summary statistic
summary(difference_layer)
##     Length      Class       Mode 
##          1 SpatRaster         S4
# create a table of counts
difference_layer %>% 
  as.data.frame() %>% 
  table()
## inhabitants_cologne
##    -2    -1     0 
##    11  2052 11711